import Vue from 'vue'
import VueRouter from 'vue-router'
import state from '../store/state'

// 个人中心
import mineRouter from './mine/mine'
// 订单
import orderRouter from './order/order'

const DashBoard = () => import('../views/dashboard')
// Tarbar
const Home = () => import('../views/home')
const Category = () => import('../views/category')
const Cart = () => import('../views/cart')
// 登录
const Login = () => import('../views/login')
// 地图
const Map = () => import('@/views/home/Map')
// 商品详情页
const GoodsDetail = () => import('@/components/common/goodsDetail/GoodsDetail')

// 解决多次点击重复路由报错
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location) {
  return originalPush.call(this, location).catch(err => err)
}

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/dashboard',
    // 是否数据缓存
    meta: {
      keepAlive: true
    }
  },
  {
    name: 'Dashboard',
    path: '/dashboard',
    component: DashBoard,
    children: [
      {
        path: '/dashboard',
        redirect: '/dashboard/home',
        meta: {
          keepAlive: true
        }
      },
      {
        name: 'Home',
        path: 'home',
        component: Home,
        meta: {
          keepAlive: true
        }
      },
      {
        name: 'Category',
        path: 'category',
        component: Category,
        meta: {
          keepAlive: true
        }
      },
      {
        name: 'Cart',
        path: 'cart',
        component: Cart,
        meta: {
          keepAlive: true
        }
      },
      mineRouter,
      {
        path: 'map',
        name: 'Map',
        component: Map
      },
      {
        path: '/goodsDetail',
        name: 'GoodsDetail',
        component: GoodsDetail
      }
    ]
  },
  {
    name: 'Login',
    path: '/login',
    component: Login
  },
  orderRouter
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  // 解决路由跳转页面没有置顶
  scrollBehavior (to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition
    } else {
      return {
        x: 0,
        y: 0
      }
    }
  },
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  if (to.meta.requireAuth) {
    if (state.userInfo.token) {
      next()
    } else {
      next({ path: '/login' })
    }
  } else {
    next()
  }
})

export default router
